package com.mdtx.base.exception;

import com.mdtx.base.ResultData;
import com.mdtx.base.SystemErrorCode;
import com.mdtx.utils.LogHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 猫啊
 * @create 2017-08-20 18:58
 **/
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultData<String> defaultHanler(HttpServletRequest req, Exception e) throws Exception {
        ResultData<String> resultData = new ResultData<>();
        Integer code = SystemErrorCode.SYS_ERR.getCode();
        String message = SystemErrorCode.SYS_ERR.getErrorInfo();
        resultData.setCode(code);
        resultData.setMessage(message);
        LogHelper.error(e.getMessage(),e,GlobalExceptionHandler.class);
        return resultData;
    }

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public ResultData<String> BaseExceptionHandler(HttpServletRequest req, BaseException e) {

       ResultData<String> resultData = new ResultData<>();
       Integer code = SystemErrorCode.SYS_ERR.getCode();
       String message = SystemErrorCode.SYS_ERR.getErrorInfo();

       if(null != e){
           LogHelper.error(e.getMessage(),e,GlobalExceptionHandler.class);
           code = e.getCode();
           message = e.getMessage();
       }else{
           LogHelper.error("Unable to get exception information beacuse Exception is "+e);
       }

       resultData.setCode(code);
       resultData.setMessage(message);

       return resultData;

    }
}
